/* 方便的方波产生器，使用T/C2 */
#include "config.h"
#ifdef TIMER2_H_INCLUDED

static INT32 cnttar = 0;
static INT32 cmpcnt = 0;
static MsgBox *tbox = NULL;
static Message    compared;
static const UINT32 TIMER2_ADJ_LIM = 30000;
const Message * const timer2Comp = &compared;
void timer2Init( UINT8 ocr )
{
	SBI( DDRB, PB7 );
	CBI( PORTB, PB7 );
	TCCR2 = 0;//stop timer2 first
	cmpcnt = 0;
	OCR2 = ocr;
	TCCR2 = _BV(WGM21) | _BV(COM20);
	SBI( TIMSK, OCIE2 );
}
inline void timer2SetCount( INT32 cnt )
{
	cmpcnt = cnt;
}
inline INT32 timer2GetCount( void )
{
	return cmpcnt;
}
void timer2SetNotice( INT32 count, MsgBox *mb )
{
	cnttar = count;
	tbox = mb;
}

DEF_OSISR( TIMER2_COMP_vect )
{
	enterKernel();
	TCNT2 = 0;
	++cmpcnt;
	if( tbox != NULL && cmpcnt > cnttar ){
		timer2Stop();
		sendMsgInt( tbox, &compared );
		cmpcnt = 0;
	}
	enterTask();
}
#endif
